package com.campuscarbooking.api.service.impl;

import com.campuscarbooking.api.service.WechatService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@RequiredArgsConstructor
@Slf4j
public class WechatServiceImpl implements WechatService {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    @Value("${wx.miniapp.appid}")
    private String appid;

    @Value("${wx.miniapp.secret}")
    private String secret;

    @Override
    public String getOpenidByCode(String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                    "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

            String response = restTemplate.getForObject(url, String.class);
            JsonNode jsonNode = objectMapper.readTree(response);

            if (jsonNode.has("errcode") && jsonNode.get("errcode").asInt() != 0) {
                log.error("微信授权失败: {}", response);
                return null;
            }

            return jsonNode.get("openid").asText();
        } catch (Exception e) {
            log.error("获取微信openid异常", e);
            return null;
        }
    }
} 